<template>
  <Category :scene="scene"></Category>
  <el-card style="margin-top: 20px">
    <div v-if="scene === 0">
      <el-button
        type="primary"
        style="margin-bottom: 20px"
        :disabled="!categoryStore.c3Id"
        @click="addAttr"
        >添加属性</el-button
      >
      <el-table :border="true" :data="attrList">
        <el-table-column label="序号" type="index" width="180" align="center" />
        <el-table-column label="属性名称" prop="attrName" />
        <el-table-column label="属性值名称">
          <template #default="{ row }">
            <el-tag
              type="primary"
              v-for="value in row.attrValueList"
              style="margin: 5px"
              >{{ value.valueName }}</el-tag
            >
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-button
              type="warning"
              icon="Edit"
              @click="updateArr(row)"
            ></el-button>
            <el-popconfirm
              :title="`您确定要删除:${row.attrName}?`"
              width="300px"
              @confirm="deleAttr(row.id)"
            >
              <template #reference>
                <el-button type="danger" icon="Delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="scene === 1">
      <el-form :inline="true">
        <el-form-item label="属性名称">
          <el-input v-model="attrParams.attrName"></el-input>
        </el-form-item>
      </el-form>
      <el-button
        type="primary"
        icon="Plus"
        :disabled="attrParams.attrName.trim() ? false : true"
        @click="addAttrValue"
        >添加属性值</el-button
      >
      <el-button type="primary" @click="cancel">取消</el-button>
      <el-table
        border
        style="margin: 20px 0px"
        :data="attrParams.attrValueList"
      >
        <el-table-column
          label="序号"
          type="index"
          width="100px"
          align="center"
        ></el-table-column>
        <el-table-column label="属性值">
          <template #default="{ row, $index }">
            <el-input
              :ref="
                (vc: any) => {
                  inputArr[$index] = vc
                }
              "
              v-if="row.flag"
              v-model="row.valueName"
              type="string"
              placeholder="请输入属性值名称"
              @blur="toLook(row, $index)"
            ></el-input>
            <div v-else @click="toEdit($index)">{{ row.valueName }}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button
              icon="delete"
              type="danger"
              size="small"
              @click="attrParams.attrValueList.splice($index, 1)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-button
        type="primary"
        @click="save"
        :disabled="attrParams.attrValueList.length > 0 ? false : true"
        >确认</el-button
      >
      <el-button type="primary" @click="cancel">取消</el-button>
    </div>
  </el-card>
</template>

<script setup lang="ts">
  import { useCategoryStore } from '@/store/modules/category'
  import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
  import type {
    AttrInfoResponseData,
    AttrList,
    AttrObj,
    AttrValueObj,
  } from '@/api/product/attr/type'
  import { reqDeleteAttr, reqAddOrEditAttr } from '@/api/product/attr'
  import { ElMessage } from 'element-plus'
  let categoryStore = useCategoryStore()
  let attrList = ref<AttrList>([])

  //定义card组件场景切换控制变量
  let scene = ref<number>(0)
  //搜集属性和属性值数据，用于添加或修改
  let attrParams = reactive<AttrObj>({
    attrName: '',
    categoryId: '',
    categoryLevel: 3,
    attrValueList: [],
  })
  //收集输入框实例,用focus()控制聚焦
  let inputArr = ref<any>([])

  watch(
    () => categoryStore.c3Id,
    () => {
      attrList.value = []
      if (!categoryStore.c3Id) return
      getAttr()
    },
  )

  const getAttr = async () => {
    let result: AttrInfoResponseData = await categoryStore.getAttrInfoList()
    if (result.code === 200) {
      attrList.value = result.data
    }
  }

  //secne0,添加属性按钮事件回调
  const addAttr = () => {
    Object.assign(attrParams, {
      attrName: '',
      categoryId: '',
      categoryLevel: 3,
      attrValueList: [],
    })
    scene.value = 1
    //收集三级分类id信息,添加属性时要传给服务器
    attrParams.categoryId = categoryStore.c3Id
  }
  //secne0,修改属性按钮事件回调
  const updateArr = (row: AttrObj) => {
    Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
    scene.value = 1
  }

  const cancel = () => {
    scene.value = 0
  }

  const addAttrValue = () => {
    attrParams.attrValueList.push({
      valueName: '',
      flag: true, //false:浏览模式;true:编辑模式
    })
    nextTick(() => {
      inputArr.value[attrParams.attrValueList.length - 1].focus()
    })
  }

  const save = async () => {
    let result: any = await reqAddOrEditAttr(attrParams)
    if (result.code === 200) {
      scene.value = 0
      ElMessage({
        type: 'success',
        message: attrParams.id ? '修改属性成功' : '新增属性成功',
      })
      //获取最新属性与属性值
      getAttr()
    } else {
      ElMessage({
        type: 'error',
        message: attrParams.id ? '修改属性失败' : '新增属性失败',
      })
    }
  }
  //输入框失去焦点事件回调,切换为浏览模式
  const toLook = (row: AttrValueObj, index: any) => {
    if (!row.valueName.trim()) {
      attrParams.attrValueList.splice(index, 1)
      ElMessage({
        type: 'error',
        message: '属性值不能为空',
      })
      return
    }
    let isRepeat = attrParams.attrValueList.find((item) => {
      //把当前失去焦点属性值对象从数组中扣除
      if (item != row) {
        return item.valueName == row.valueName
      }
    })
    if (isRepeat) {
      attrParams.attrValueList.splice(index, 1)
      ElMessage({
        type: 'error',
        message: '不能有重复属性值',
      })
      return
    }
    attrParams.attrValueList[index].flag = false
  }

  //点击div元素时再切换为编辑模式
  const toEdit = (index: any) => {
    attrParams.attrValueList[index].flag = true
    nextTick(() => {
      inputArr.value[index].focus()
    })
  }

  //删除属性事件回调
  const deleAttr = async (attrId: number) => {
    let result = await reqDeleteAttr(attrId)
    if (result.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除该属性成功',
      })
      getAttr()
    } else {
      ElMessage({
        type: 'error',
        message: '删除该属性失败',
      })
    }
  }

  onBeforeUnmount(() => {
    categoryStore.$reset()
  })
</script>

<style scoped></style>
